package com.itheima.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.concurrent.TimeUnit;

import static com.itheima.util.RedisConstants.*;

public class LoginInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;
    public LoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String employee = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY);
        String user = stringRedisTemplate.opsForValue().get(LOGIN_USER_KEY);
        if (employee == null) {
            return false;
        }
        Long employeeId = Long.valueOf(employee);
        BaseContext.setCurrentId(employeeId);
        //
        Long userId = Long.valueOf(user);
        UserHolder.saveUserId(userId);
        //刷新redis登入时长
        //设置有效期
        stringRedisTemplate.expire(LOGIN_CODE_KEY,LOGIN_CODE_TTL, TimeUnit.MINUTES);
        return true;
    }
}
